# Maintainer: Martell Malone <martellmalone@gmail.com>
# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Ray Donnelly <mingw.android@gmail.com>
# Contributor: Mateusz Mikuła <mati865@gmail.com>
# Contributor: wirx6 <wirx654@gmail.com>
# Contributor: Yuui Tanabe <yuuitanabe@163.com>
# Contributor: Oscar Fuentes <ofv@wanadoo.es>
# Contributor: Adrian Pop <adrian.pop@liu.se>

_compiler=gcc
if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
  _clangprefix=1
  _compiler=clang
fi
_realname=clang
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-clang-analyzer"
         "${MINGW_PACKAGE_PREFIX}-clang-tools-extra"
         "${MINGW_PACKAGE_PREFIX}-compiler-rt"
         "${MINGW_PACKAGE_PREFIX}-lld"
         "${MINGW_PACKAGE_PREFIX}-llvm")
pkgver=13.0.0
pkgrel=3
pkgdesc="C language family frontend for LLVM (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://llvm.org/"
license=("custom:Apache 2.0 with LLVM Exception")
groups=($( (( _clangprefix )) && echo "${MINGW_PACKAGE_PREFIX}-toolchain"))
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake>=3.4.3"
             "${MINGW_PACKAGE_PREFIX}-z3"
             "${MINGW_PACKAGE_PREFIX}-libffi"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-pkg-config"
             "${MINGW_PACKAGE_PREFIX}-python-sphinx"
             "${MINGW_PACKAGE_PREFIX}-python"
             "tar"
             "groff"
             $([[ "$_compiler" == "clang" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-clang" \
               "${MINGW_PACKAGE_PREFIX}-compiler-rt" \
               "${MINGW_PACKAGE_PREFIX}-libc++")
             $([[ "$_compiler" == "gcc" ]] && echo \
               "${MINGW_PACKAGE_PREFIX}-gcc")
             )
options=('!debug' 'strip')
_url=https://github.com/llvm/llvm-project/releases/download/llvmorg-${pkgver}
# libunwind: # https://bugs.llvm.org/show_bug.cgi?id=49228
source=("${_url}/llvm-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/clang-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/clang-tools-extra-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/compiler-rt-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/lld-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/libunwind-${pkgver}.src.tar.xz"{,.sig}
        "0001-Use-posix-style-path-separators-with-MinGW.patch"
        "0002-Fix-GetHostTriple-for-mingw-w64-in-msys.patch"
        "0003-CMake-try-creating-symlink-first-on-windows.patch"
        "0005-add-pthread-as-system-lib-for-mingw.patch"
        "0008-enable-emutls-for-mingw.patch"
        "0009-export-out-of-tree-mlir-targets.patch"
        "0101-Disable-fPIC-errors.patch"
        "0103-Use-posix-style-path-separators-with-MinGW.patch"
        "0104-link-pthread-with-mingw.patch"
        "0105-clang-Tooling-Use-Windows-command-lines.patch"
        "0304-ignore-new-bfd-options.patch")
# Some patch notes :)
#0001-0099 -> llvm
#0101-0199 -> clang
#0201-0299 -> rt
#0301-0399 -> lld
sha256sums=('408d11708643ea826f519ff79761fcdfc12d641a2510229eec459e72f8163020'
            'SKIP'
            '5d611cbb06cfb6626be46eb2f23d003b2b80f40182898daa54b1c4e8b5b9e17e'
            'SKIP'
            '428b6060a28b22adf0cdf5d827abbc2ba81809f4661ede3d02b1d3fedaa3ead5'
            'SKIP'
            '4c3602d76c7868a96b30c36165c4b7643e2a20173fced7e071b4baeb2d74db3f'
            'SKIP'
            '20d1900bcd64ff62047291f6edb6ba2fed34d782675ff68713bf0c2fc9e69386'
            'SKIP'
            '36f819091216177a61da639244eda67306ccdd904c757d70d135e273278b65e1'
            'SKIP'
            '403f1711270ab62988d9f6a111a95049711cb36be6763025734ff4ded4b5e091'
            '8831c6ea72baa315b20e5f1a9008a9bf4098ba8a18d5331f05216604489063a4'
            '5cd56dd01716a37ef6981793a57bea07260b44d91592c1d8b8bde0c3497884f0'
            '7f0c64cd87b61e894be632f180ae5291e1aa9f1d9d382608f659067eeeda7146'
            '3837bd707d3d99a742e874d5c59a1e7d5502811d6926319974c5d9db86020039'
            'cb96582194ef80a37cc184e95287920b2df5369e2e5798a64adf6f8bf1c52985'
            '63b2bda6a487ec69e257c3b7a14d71f6bec649fca058a5a54804f213d45c7c70'
            '2d1dc7f7cd6bd61f275cd0be6650f3086aee622074ac786ff5a921bf8ecaada2'
            '715cb8862753854b2d9256e0b70003e2d1f57083d83eaeaf5a095fc72b8a4e26'
            'ccc70ac6cdca113fcf0d2ecebf8fc9dcad073a67b0662f1c4af616094778a84d'
            '778e0db0a5b0657ab05e2a81d83241347a4a41af2b0f9903422f651fa58e8d40')
validpgpkeys=('B6C8F98282B944E3B0D5C2530FC3042E345AD05D'  # Hans Wennborg, Google.
              '474E22316ABF4785A88C6E8EA2C794A986419D8A') # Tom Stellard
noextract=(clang-${pkgver}.src.tar.xz)

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

revert_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Reverting ${_patch}"
    patch -Rbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}"
  plain "Extracting clang-${pkgver}.src.tar.xz due to symlink(s) without pre-existing target(s)"
  tar -xJf ${srcdir}/clang-${pkgver}.src.tar.xz -C ${srcdir} || true

  # Rename Directories
  for pkg in llvm clang clang-tools-extra compiler-rt lld libunwind; do
    mv ${pkg}-$pkgver.src ${pkg}
  done

  cd "${srcdir}/llvm"
  apply_patch_with_msg \
    "0001-Use-posix-style-path-separators-with-MinGW.patch" \
    "0002-Fix-GetHostTriple-for-mingw-w64-in-msys.patch"

  revert_patch_with_msg \
    "0003-CMake-try-creating-symlink-first-on-windows.patch"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0005-add-pthread-as-system-lib-for-mingw.patch" \
      "0008-enable-emutls-for-mingw.patch"
  fi

  apply_patch_with_msg \
    "0009-export-out-of-tree-mlir-targets.patch"

  cd "${srcdir}/clang"
  apply_patch_with_msg \
    "0101-Disable-fPIC-errors.patch" \
    "0103-Use-posix-style-path-separators-with-MinGW.patch" \
    "0105-clang-Tooling-Use-Windows-command-lines.patch"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0104-link-pthread-with-mingw.patch"
  fi

  cd "${srcdir}/lld"

  apply_patch_with_msg \
    "0304-ignore-new-bfd-options.patch"
}

build() {
  cd "${srcdir}"

  case "${CARCH}" in
    i?86|armv7)
      # lld needs all the address space it can get.
      LDFLAGS+=" -Wl,--large-address-aware"
      ;;
  esac

  local -a platform_config
  local -a common_cmake_args

  if check_option "debug" "y"; then
    common_cmake_args+=(-DCMAKE_BUILD_TYPE=Debug)
    VERBOSE="VERBOSE=1"
  else
    common_cmake_args+=(-DCMAKE_BUILD_TYPE=Release)
  fi
  common_cmake_args+=(-Wno-dev
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX}
    -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib
    -DLLVM_HOST_TRIPLE="${CARCH}-w64-windows-gnu"
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe
    -DPython3_FIND_REGISTRY=NEVER
    -DPython3_ROOT_DIR=${MINGW_PREFIX})

  # Include location of libffi headers in CPPFLAGS
  FFI_INCLUDE_DIR="$(pkg-config --cflags libffi)"
  FFI_INCLUDE_DIR=$(echo $FFI_INCLUDE_DIR | sed 's|-I||g')

  if [ "${_compiler}" == "clang" ]; then
    export CC='clang'
    export CXX='clang++'
    platform_config+=(-DCOMPILER_RT_USE_BUILTINS_LIBRARY=ON
      -DLLVM_ENABLE_LIBCXX=ON)
  fi

  if (( _clangprefix )); then
    # A bit hacky but it works
    local _clang_links="clang++;clang-cpp;as;c++;cc;cpp;g++;gcc;${MINGW_CHOST}-cc;${MINGW_CHOST}-c++;${MINGW_CHOST}-clang;${MINGW_CHOST}-clang++;${MINGW_CHOST}-g++;${MINGW_CHOST}-gcc"

    platform_config+=(-DCLANG_DEFAULT_RTLIB=compiler-rt
      -DCLANG_DEFAULT_UNWINDLIB=libunwind
      -DCLANG_DEFAULT_CXX_STDLIB=libc++
      -DCLANG_DEFAULT_LINKER=lld
      -DLLVM_ENABLE_LLD=ON
      -DCLANG_LINKS_TO_CREATE="${_clang_links}"
      -DLLVM_INSTALL_BINUTILS_SYMLINKS=ON)
  fi

  local _projects="clang;clang-tools-extra;compiler-rt;lld"

  case "${CARCH}" in
    x86_64|i?86)
      platform_config+=(-DCOMPILER_RT_BUILD_SANITIZERS=$( (( _clangprefix )) && echo "ON" || echo "OFF"))
      ;;
    armv7|aarch64)
      platform_config+=(-DCOMPILER_RT_BUILD_MEMPROF=OFF
        -DCOMPILER_RT_BUILD_SANITIZERS=OFF
        -DCOMPILER_RT_BUILD_XRAY=OFF)
      ;;
  esac

  [[ -d build-${MSYSTEM} ]] && rm -rf build-${MSYSTEM}
  mkdir build-${MSYSTEM} && cd build-${MSYSTEM}

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -GNinja \
    -DFFI_INCLUDE_DIR="${FFI_INCLUDE_DIR}" \
    -DLIBCLANG_BUILD_STATIC=ON \
    -DLLD_DEFAULT_LD_LLD_IS_MINGW=ON \
    -DLLVM_BUILD_LLVM_DYLIB=ON \
    -DLLVM_BUILD_STATIC=OFF \
    -DLLVM_ENABLE_ASSERTIONS=OFF \
    -DLLVM_ENABLE_FFI=ON \
    -DLLVM_ENABLE_PROJECTS="${_projects}" \
    -DLLVM_ENABLE_SPHINX=ON \
    -DLLVM_ENABLE_THREADS=ON \
    -DLLVM_INCLUDE_EXAMPLES=OFF \
    -DLLVM_INSTALL_UTILS=ON \
    -DLLVM_LINK_LLVM_DYLIB=ON \
    -DLLVM_TARGETS_TO_BUILD="AArch64;AMDGPU;ARM;AVR;BPF;MSP430;NVPTX;RISCV;WebAssembly;X86" \
    "${common_cmake_args[@]}" \
    "${platform_config[@]}" \
    ../llvm

  ${MINGW_PREFIX}/bin/cmake.exe --build .

  # Disable automatic installation of components that go into subpackages
  # -i.orig to check what has been removed in-case it starts dropping more than it should
  #
  sed -i.orig '/\(clang\|lld\)\/cmake_install.cmake/d' tools/cmake_install.cmake
  sed -i.orig '/\(extra\|scan-build\|scan-build-py\|scan-view\)\/cmake_install.cmake/d' tools/clang/tools/cmake_install.cmake
  sed -i.orig '/compiler-rt\/cmake_install.cmake/d' projects/cmake_install.cmake
}

check() {
 cd "${srcdir}"/build-${MSYSTEM}
 # Remove || true once testcase doesn't cause failures.
#  make check || true
#  make check-clang || true
  ${MINGW_PREFIX}/bin/cmake.exe --build . -- check-lld || true
}

package_clang() {
  pkgdesc="C language family frontend for LLVM (mingw-w64)"
  url="https://clang.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm=${pkgver}"
           $( ((_clangprefix)) && echo \
             "${MINGW_PACKAGE_PREFIX}-compiler-rt=${pkgver}" \
             "${MINGW_PACKAGE_PREFIX}-crt" \
             "${MINGW_PACKAGE_PREFIX}-headers" \
             "${MINGW_PACKAGE_PREFIX}-lld=${pkgver}" \
             "${MINGW_PACKAGE_PREFIX}-winpthreads" \
             || echo "${MINGW_PACKAGE_PREFIX}-gcc"))
  provides=($( (( _clangprefix )) && echo \
             "${MINGW_PACKAGE_PREFIX}-gcc" \
             || true ))

  cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang" --prefix "${pkgdir}${MINGW_PREFIX}"
}

package_clang-analyzer() {
  pkgdesc="A source code analysis framework (mingw-w64)"
  url="https://clang-analyzer.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-clang=${pkgver}"
           "${MINGW_PACKAGE_PREFIX}-python")

  local _analyzer
  for _analyzer in scan-build scan-build-py scan-view; do
    DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang/tools/${_analyzer}"
  done

  # Compile Python scripts
  ${MINGW_PREFIX}/bin/python -m compileall "${pkgdir}"${MINGW_PREFIX}/lib/libscanbuild
  ${MINGW_PREFIX}/bin/python -O -m compileall "${pkgdir}"${MINGW_PREFIX}/lib/libscanbuild

  install -Dm644 "${srcdir}/clang/LICENSE.TXT" "${pkgdir}"${MINGW_PREFIX}/share/licenses/clang-analyzer/LICENSE
}

package_clang-tools-extra() {
  pkgdesc="Extra tools built using Clang's tooling APIs (mingw-w64)"
  url="https://clang.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-clang=${pkgver}")

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang/tools/extra"
}

package_compiler-rt() {
  pkgdesc="Runtime libraries for Clang and LLVM (mingw-w64)"
  url="https://compiler-rt.llvm.org/"
  depends=($( (( _clangprefix )) || echo "${MINGW_PACKAGE_PREFIX}-gcc-libs"))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/projects/compiler-rt"
  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin/"
  find "${pkgdir}${MINGW_PREFIX}/lib/clang/${pkgver}/lib/windows/" \
    -name '*.dll' -exec mv '{}' "${pkgdir}${MINGW_PREFIX}/bin/" \;
  # remove bin dir we created if it is still empty
  rmdir "${pkgdir}${MINGW_PREFIX}/bin/" 2>/dev/null || true
}

package_lld() {
  pkgdesc="Linker tools for LLVM (mingw-w64)"
  url="https://lld.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm=${pkgver}")
  provides=($( (( _clangprefix )) && echo \
             "${MINGW_PACKAGE_PREFIX}-binutils" \
             || true))

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}/tools/lld"
  if (( _clangprefix )); then
    install -Dm755 "${pkgdir}${MINGW_PREFIX}/bin/lld.exe" "${pkgdir}${MINGW_PREFIX}/bin/ld.exe"
  fi
}

package_llvm() {
  pkgdesc="Low Level Virtual Machine (mingw-w64)"
  depends=("${MINGW_PACKAGE_PREFIX}-libffi"
           "${MINGW_PACKAGE_PREFIX}-gcc-libs"
           "${MINGW_PACKAGE_PREFIX}-zlib"
           "${MINGW_PACKAGE_PREFIX}-libxml2")

  cd "${srcdir}"/llvm

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}"

  install -Dm644 "${srcdir}/llvm/LICENSE.TXT" "${pkgdir}${MINGW_PREFIX}/share/licenses/llvm/LICENSE"

  # Install CMake stuff
  install -d "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/{modules,platforms}
  install -Dm644 "${srcdir}"/llvm/cmake/modules/*.cmake "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/modules/
  install -Dm644 "${srcdir}"/llvm/cmake/platforms/*.cmake "${pkgdir}"${MINGW_PREFIX}/share/llvm/cmake/platforms/

  # fix cmake files.
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  sed -e "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i ${pkgdir}/${MINGW_PREFIX}/lib/cmake/llvm/LLVMExports.cmake
}

# template start; name=mingw-w64-splitpkg-wrappers; version=1.0;
# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
# template end;
